<!-- 申请分销商 -->
<template>
	<view class="apply-commission-wrap">
		<view class="commission-wrap"
			:class="{ blur: !hasAuth }"
			v-if="formList.length">
			<!-- 标题栏 -->
			<view class="head-box">
				<image :src="formHeadImg"
					mode="widthFix"
					class="bg"></image>
				<shopro-navbar back-icon-color="#fff"
					:background="{}"></shopro-navbar>
			</view>
			<!-- 表单 -->
			<view class="apply-form">
				<u-form ref="uForm"
					:errorType="errorType">
					<block v-for="(form, index) in formList"
						:key="index">
						<u-form-item :labelStyle="labelStyle"
							label-width="150"
							label-position="left"
							:label="form.name"
							:prop="`{form.key}`"
							v-if="form.type === 'select'">
							<picker mode="selector"
								:range="form.option"
								range-key="name"
								@change="selectChange($event,index)"
								v-if="hasPostBtn">
								<view class="picker">
									<view class=""
										v-if="form.value !== '' && form.option[form.value]">
										{{form.option[form.value].name}}
									</view>
									<view class="placeholder"
										v-else>
										{{form.placeholder}}
									</view>
									<text class="u-iconfont uicon-arrow-right u-m-l-10"
										style="color: #b1b1b1;font-size: 28rpx;"></text>
								</view>
							</picker>
							<view class="value"
								v-else>{{form.value}}</view>
						</u-form-item>
						<u-form-item :labelStyle="labelStyle"
							label-width="150"
							label-position="left"
							:label="form.name"
							:prop="`{form.key}`"
							v-else-if="form.type === 'date'">
							<picker mode="date"
								:range="form.option"
								range-key="name"
								@change="selectChange($event,index)"
								v-if="hasPostBtn">
								<view class="picker">
									<view class=""
										v-if="form.value !== ''">
										{{form.value}}
									</view>
									<view class="placeholder"
										v-else>
										{{form.placeholder}}
									</view>
									<text class="u-iconfont uicon-arrow-right u-m-l-10"
										style="color: #b1b1b1;font-size: 28rpx;"></text>
								</view>
							</picker>
							<view class="value"
								v-else>{{form.value}}</view>
						</u-form-item>
						<u-form-item :labelStyle="labelStyle"
							label-width="150"
							label-position="left"
							:label="form.name"
							:prop="`{form.key}`"
							v-else-if="form.type === 'text'">
							<u-input :placeholder="form.placeholder"
								v-model="form.value"
								type="text"
								input-align="right"
								:disabled="form.disabled"
								:custom-style="form.disabled ? {color: '#bbbbbb'} : {}"
								v-if="hasPostBtn"></u-input>
							<view class="value"
								v-else>{{form.value || '无'}}</view>
						</u-form-item>
						<u-form-item :labelStyle="labelStyle"
							label-width="150"
							label-position="left"
							:label="form.name"
							:prop="`{form.key}`"
							v-else-if="form.type === 'code' && hasPostBtn">
							<u-input :placeholder="form.placeholder"
								v-model="form.value"
								type="text"
								input-align="right"
								:disabled="form.disabled">
							</u-input>
							<button class="u-reset-button code-btn code-btn-start code-btn-end"
								@tap="getSmsCode('register')"
								slot="right">
								{{ codeText }}
							</button>
						</u-form-item>
						<u-form-item :labelStyle="labelStyle"
							label-width="500"
							label-position="top"
							:label="form.name"
							:prop="`{form.key}`"
							v-else-if="form.type === 'upload'">
							<u-upload :deletable="hasPostBtn"
								:placeholderStyle="placeholderStyle"
								:showProgress="false"
								@on-uploaded="uploadSuccess($event, index)"
								@on-remove="uploadRemove($event, index)"
								:file-list="form.fileList"
								:action="`${$BASE_URL}/api/common/upload`"
								:header="{token: token}"
								width="148"
								height="148"
								maxCount="1"
								:sizeType="['compressed']"></u-upload>
						</u-form-item>
					</block>
				</u-form>
				<view style="height: 250rpx;"
					v-if="hasPostBtn"></view>
			</view>
			<view class="cu-bar foot bg-white"
				v-if="hasPostBtn">
				<view style="padding-top: 10rpx;width: 100%;">
					<view class="agreement u-flex"
						v-if="protocol && hasPostBtn">
						<u-checkbox v-model="agreement"
							activeColor="#b095ff"
							shape="circle"
							@change="onAgreement"></u-checkbox>
						<view class="agreement-text"
							@tap="$Router.push({ path: '/pages/public/richtext', query: { id: protocol.richtext_id } })">
							我已阅读并遵守 <text>《{{ protocol.name }}》</text>
						</view>
					</view>
					<button class="u-reset-button save-btn"
						v-if="hasPostBtn"
						@tap="onSubmit"
						:disabled="isFormEnd">确认提交</button>
				</view>
			</view>
		</view>
		<!-- 佣金中心权限验证 -->
		<u-popup v-if="showAuthModal"
			class="auth-box"
			:mask="false"
			v-model="showAuthModal"
			mode="center"
			:mask-close-able="false"
			close-icon-pos="top-left"
			border-radius="20">
			<view class="notice-box">
				<view class="img-wrap">
					<image class="notice-img"
						:src="authNotice.img"
						mode=""></image>
				</view>
				<view class="notice-title">{{ authNotice.title }}</view>
				<view class="notice-detail">{{ authNotice.detail }}</view>
				<button class="u-reset-button notice-btn"
					@tap="onAuthBtn(authNotice.btnPath)">{{ authNotice.btnText }}</button>
				<button class="u-reset-button back-btn"
					@tap="$Router.back()"
					v-if="!authNotice.hideBtn">返回</button>
				<button class="u-reset-button back-btn"
					@tap="hasAuth = true"
					v-else>取消</button>
			</view>
		</u-popup>
	</view>
</template>
<script>
	import share from '@/shopro/share'
	export default {
		components: {},
		data() {
			return {
				formList: [], //返回的表单
				formHeadImg: '', //表单头部背景
				protocol: null, //协议
				isFormEnd: false, //提交成功
				hasPostBtn: false, //是否显示提交按钮
				errorType: ['message'],
				labelStyle: {
					'font-size': '28rpx',
					'font-weight': '500',
					color: '#333'
				},
				placeholderStyle: 'font-size: 28rpx;color:#c4c4c4;',
				token: uni.getStorageSync('token'),
				codeText: "获取验证码",
				agreement: false,
				authNotice: {},
				hasAuth: true, //是否有权限
				shareParams: ''
			};
		},
		computed: {
			showAuthModal: {
				get() {
					return !!this.authNotice.title && !this.hasAuth;
				},
				set(val) {
					return val;
				}
			}
		},
		onLoad() {
			let spm = uni.getStorageSync("spm")
			if(spm){
				this.shareParams = share.getShareQuery(spm)
			}
			this.getFrom();
		},
		methods: {
			// 权限
			onAuthBtn(path) {
				path ? this.$Router.push({
					path: path
				}) : this.$Router.back();
			},
			// 获取短信验证码
			getSmsCode(type) {
				const that = this;
				let mobileIndex = this.formList.findIndex((item) => {
					return item.key == "mobile"
				})
				let mobile = this.formList[mobileIndex].value
				if (mobile) {
					that.$http("common.smsSend", {
						mobile,
						event: type
					}, "获取验证码中...").then(res => {
						if (res.code === 1) {
							that.codeChange();
							that.$u.toast("验证码已发送，请注意查收短信");
						} else {
							that.$u.toast(res.msg);
						}
					});
				} else {
					that.$u.toast("请输入手机号码");
				}
			},
			// 倒计时
			codeChange() {
				if (this.disabledCode) return;
				this.disabledCode = true;
				let n = 60;
				this.codeText = n + "s";
				const run = setInterval(() => {
					n -= 1;
					if (n < 0) {
						clearInterval(run);
					}
					this.codeText = n + "s";
					if (this.codeText < 0 + "s") {
						this.disabledCode = false;
						this.codeText = "重新获取";
					}
				}, 1000);
			},
			// 选择
			selectChange(e, index) {
				this.formList[index].value = e.detail.value
			},
			// 上传图片成功-单图
			uploadSuccess(e, index) {
				let that = this
				let url = e[0].response.data.url
				this.formList[index].value = url
				if (this.formList[index].key == "front_img") {
					uni.showLoading()
					this.$http('common.ocr', {
						ocrType: "id_card-face",
						image: url
					}).then(res => {
						res.data.map((item, index) => {
							if (item.key == "name") {
								let nameIndex = that.formList.findIndex((item, index) => {
									return item.key == 'realname'
								})
								that.formList[nameIndex].value = item.value
							} else if (item.key == "num") {
								let idcardIndex = that.formList.findIndex((item, index) => {
									return item.key == 'idcard'
								})
								that.formList[idcardIndex].value = item.value
							}
						})
					})
				}
			},
			// 移除图片
			uploadRemove(e, index) {
				this.formList[index].value = ''
			},
			// 勾选同意
			onAgreement(e) {
				this.agreement = e.value;
			},
			// 获取申请分销商表单
			getFrom() {
				let that = this;
				that.$http('commission.form').then(res => {
					if (res.code === 1) {
						if (res.data.status == 'forbidden') {
							uni.redirectTo({
								url: "/pages/app/commission/index"
							})
							return false
						}
						that.protocol = res.data.apply_protocol; //表单协议同
						// 等级
						let level = ''
						// 分享人
						let share_id = ''
						let formList = [{
							name: "学校",
							key: "school",
							placeholder: "选择学校",
							type: 'select',
							option: res.data.school_list,
							value: '',
							required: true
						}, {
							name: "学历",
							key: "education",
							placeholder: "选择学历",
							type: 'select',
							option: res.data.education_list,
							value: '',
							required: true
						}, {
							name: "入学时间",
							key: "intake",
							placeholder: "选择入学时间",
							type: 'date',
							value: '',
							required: true
						}, {
							name: "学院专业",
							key: "major",
							placeholder: "请输入所在学院专业",
							type: 'text',
							value: '',
							disabled: false,
							required: true
						}, {
							name: "学生证第一页",
							key: "student_img",
							placeholder: "请上传学生证第一页",
							type: 'upload',
							value: '',
							fileList: [],
							required: true
						}, {
							name: "身份证正面",
							key: "front_img",
							placeholder: "请上传身份证正面",
							type: 'upload',
							value: '',
							fileList: [],
							required: true
						}, {
							name: "身份证反面",
							key: "back_img",
							placeholder: "请上传身份证反面",
							type: 'upload',
							value: '',
							fileList: [],
							required: true
						}, {
							name: "真实姓名",
							key: "realname",
							placeholder: "上传身份证正面后获取",
							type: 'text',
							value: '',
							disabled: false,
							required: true
						}, {
							name: "身份证号码",
							key: "idcard",
							placeholder: "上传身份证正面后获取",
							type: 'text',
							value: '',
							disabled: false,
							required: true
						}, {
							name: "手机号码",
							key: "mobile",
							placeholder: "请输入11位手机号码",
							type: 'text',
							value: '',
							disabled: false,
							required: true
						}, 
						// {
						// 	name: "验证码",
						// 	key: "code",
						// 	placeholder: "请输入验证码",
						// 	type: 'code',
						// 	value: '',
						// 	disabled: false,
						// 	required: true
						// }, 
						{
							name: "推荐人ID",
							key: "share_id",
							placeholder: "请输入推荐ID-(自动获取)",
							type: 'text',
							value: '',
							disabled: false,
							required: false
						}, {
							name: "分销商等级",
							key: "level",
							placeholder: "选择分销商等级",
							type: 'select',
							option: res.data.level_list,
							value: '',
							required: true
						}]
						let apply_info = {}
						if (res.data.apply_info) {
							res.data.apply_info.map((item) => {
								if (item.type == "image") {
									item.value = {
										fileList: [{
											url: this.$BASE_URL + item.value
										}],
										value: item.value
									}
								} else if (item.key == "school" && res.data.apply_status) {
									let schoolIndex = res.data.school_list.findIndex((school) => {
										return school.name == item.value
									})
									item.value = schoolIndex !== -1 ? schoolIndex : ''
								} else if (item.key == "education" && res.data.apply_status) {
									let educationIndex = res.data.education_list.findIndex((education) => {
										return education.name == item.value
									})
									item.value = educationIndex !== -1 ? educationIndex : ''
								} else if (item.key == 'level') {
									level = item.value
								} else if (item.key == 'share_id') {
									share_id = item.value
								}
								apply_info[item.key] = item.value
							})
						}
						if (((res.data.apply_info && !res.data.apply_info.pay_status) || !res.data.apply_info) &&
							res.data.share && res.data.apply_status) {
							level = res.data.share.level || level
							share_id = res.data.share.share_id
						}
						if(that.shareParams){
							level = that.shareParams.level || level
							share_id = that.shareParams.shareUserId || share_id
						}
						for (let i = 0; i < formList.length; i++) {
							if (apply_info[formList[i].key] || apply_info[formList[i].key] == 0) {
								if (formList[i].type == 'upload') {
									formList[i].value = apply_info[formList[i].key].value
									formList[i].fileList = apply_info[formList[i].key].fileList
								} else {
									formList[i].value = apply_info[formList[i].key]
								}
							}
							if (formList[i].key == 'share_id' && share_id) {
								formList[i].disabled = true
								formList[i].value = share_id
							} else if (formList[i].key == 'level' && level) {
								let levelIndex = res.data.level_list.findIndex((item) => {
									return item.level == level
								})
								if (levelIndex !== -1) {
									formList[i].value = res.data.apply_status ? 0 : res.data.level_list[levelIndex]
										.name
									formList[i].option = [res.data.level_list[levelIndex]]
								} else {
									formList[i].value = 0
									formList[i].option = res.data.level_list
								}
							}
						}
						that.formList = formList
						that.hasPostBtn = res.data.apply_status; //是否显示提交按钮
						that.formHeadImg = res.data.background_image ? res.data.background_image : this.$IMG_URL +
							'/imgs/commission/apply_bg.png'; //头部背景
						that.authStatus(res.data)
					}
				});
			},
			//申请分销商
			applyCommission(data) {
				let that = this;
				that.isFormEnd = true;
				that.$http('commission.apply', data, '申请中...').then(res => {
					that.isFormEnd = false;
					if (res.code === 1) {
						if (res.data.pay_status == 0) {
							that.$Router.push({
								path: `/pages/order/payment/method`,
								query: {
									orderId: res.data.user_id,
									orderType: 'agent'
								}
							});
						} else {
							uni.showToast({
								title: res.msg,
								success: () => {
									that.$Router.back();
								}
							});
						}
					}
				});
			},
			// 提交
			onSubmit() {
				let that = this;
				for (let i = 0; i < this.formList.length; i++) {
					if (this.formList[i].required && this.formList[i].value === '') {
						this.$u.toast(this.formList[i].placeholder)
						return false
					}
				}
				if (!this.agreement && this.protocol) return this.$u.toast('请勾选协议');
				let formData = {
					data: []
				}
				this.formList.map((item, index) => {
					if (item.key == 'code' || item.key == 'share_id') {
						formData[item.key] = item.value
					} else if (item.key == 'level') {
						formData.level = item.option[Number(item.value)].level
					} else if (item.type == 'select') {
						formData.data.push({
							name: item.name,
							type: "input",
							value: item.option[Number(item.value)].name,
							key: item.key
						})
					} else if (item.type == 'upload') {
						formData.data.push({
							name: item.name,
							type: "image",
							value: item.value,
							key: item.key
						})
					} else {
						if (item.key == 'mobile') {
							formData.mobile = item.value
						}
						formData.data.push({
							name: item.name,
							type: "input",
							value: item.value,
							key: item.key
						})
					}
				});
				this.applyCommission(formData);
			},
			// 状态鉴权
			authStatus(data) {
				switch (data.status) {
					case 'forbidden':
						this.hasAuth = false;
						this.showTerm = false;
						this.authNotice = {
							img: this.$IMG_URL + '/imgs/commission/auth_stop.png',
							title: '抱歉！你的账户已被禁用',
							detail: data.msg,
							btnText: '联系客服',
							btnPath: '/pages/public/chat/index'
						};
						break;
					case 'pending':
						this.hasAuth = false;
						this.showTerm = false;
						this.authNotice = {
							img: this.$IMG_URL + '/imgs/commission/auth_stop.png',
							title: '正在审核中！',
							detail: data.msg,
							btnText: '知道了',
							btnPath: ''
						};
						break;
						// case 'needinfo':
						// 	this.hasAuth = false;
						// 	this.authNotice = {
						// 		img: this.$IMG_URL + '/imgs/commission/auth_perfect.png',
						// 		title: '待完善信息',
						// 		detail: data.msg,
						// 		btnText: '去完善',
						// 		btnPath: '/pages/app/commission/apply'
						// 	};
						// 	break;
						// case 'reject':
						// 	this.hasAuth = false;
						// 	this.showTerm = false;
						// 	this.authNotice = {
						// 		img: this.$IMG_URL + '/imgs/commission/auth_reject.png',
						// 		title: '申请驳回',
						// 		detail: data.msg,
						// 		btnText: '修改资料',
						// 		btnPath: '/pages/app/commission/apply'
						// 	};
						// 	break;
					case 'close':
						this.hasAuth = false;
						this.showTerm = false;
						this.authNotice = {
							img: this.$IMG_URL + '/imgs/commission/auth_close.png',
							title: '分销中心已关闭',
							detail: data.msg,
							btnText: '我知道了',
							btnPath: ''
						};
						break;
					case 'freeze':
						this.hasAuth = false;
						this.showTerm = false;
						this.authNotice = {
							img: this.$IMG_URL + '/imgs/commission/auth_freeze.png',
							title: '抱歉！你的账户已被冻结',
							detail: data.msg,
							btnText: '联系客服',
							btnPath: '/pages/public/chat/index',
							hideBtn: true
						};
						break;
					case null:
						this.hasAuth = false;
						this.showTerm = true;
						if (data.become_agent) {
							if (data.become_agent.type === 'goods') {
								this.showGoodsTerm = true;
								this.getGoodsTermList(data.become_agent.value);
							}
							if (data.become_agent.type === 'consume') {
								this.showMoneyTerm = true;
								this.moneyTermNum = data.become_agent.value;
							}
						}
						break;
					default:
						this.hasAuth = true;
						this.showTerm = false;
				}
			}
		}
	};
</script>
<style lang="scss">
	/deep/ .cu-custom {
		position: absolute;
		top: 0;
		left: 0;
	}

	// 佣金中心权限验证蒙层
	.blur {
		filter: blur(20rpx);
		transition: all 0.3s ease-in-out 0s;
	}

	.auth-box {
		width: 100%;
		height: 100%;
		background: none;

		.notice-box {
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			background-color: #fff;
			width: 612rpx;
			min-height: 658rpx;
			background: #ffffff;
			padding: 30rpx;
			border-radius: 20rpx;

			.img-wrap {
				margin-bottom: 50rpx;

				.notice-img {
					width: 180rpx;
					height: 170rpx;
				}
			}

			.notice-title {
				font-size: 35rpx;
				font-weight: bold;
				color: #46351b;
				margin-bottom: 28rpx;
			}

			.notice-detail {
				font-size: 28rpx;
				font-weight: 400;
				color: #999999;
				line-height: 36rpx;
				margin-bottom: 50rpx;
			}

			.notice-btn {
				width: 492rpx;
				line-height: 70rpx;
				background: linear-gradient(-90deg, #a36fff, #5336ff);
				box-shadow: 0px 7rpx 11rpx 2rpx rgba(124, 103, 214, 0.34);
				border-radius: 35rpx;
				font-size: 28rpx;
				font-weight: 500;
				color: #ffffff;
				margin-bottom: 10rpx;
			}

			.back-btn {
				width: 492rpx;
				line-height: 70rpx;
				font-size: 28rpx;
				font-weight: 500;
				color: #c5b8fb;
				background: none;
			}
		}
	}

	.code-btn[disabled] {
		background-color: #fff;
	}

	.code-btn-start {
		width: 180rpx;
		line-height: 56rpx;
		border: 1rpx solid #e9b766;
		border-radius: 28rpx;
		font-size: 26rpx;
		font-weight: 400;
		color: #e9b766;
		opacity: 1;
		margin-left: 20rpx;
	}

	.apply-commission-wrap {
		height: 100%;
		background-color: #fff;

		.head-box {
			width: 100%;
			background-size: 100% 100%;
			background-repeat: no-repeat;
			position: relative;

			.bg {
				width: 100%;
			}
		}
	}

	// 表单
	.apply-form {
		width: 750rpx;
		background: #ffffff;
		border-radius: 20rpx;
		padding: 0 30rpx;

		.placeholder {
			color: #b1b1b1;
		}

		.value {
			flex: 1;
			text-align: right;
		}

		picker {
			width: 100%;
			text-align: right;

			.picker {
				display: flex;
				justify-content: flex-end;
				align-items: center;
			}
		}
	}

	.agreement {
		margin-top: 20rpx;
		justify-content: center;

		.agreement-text {
			font-size: 24rpx;
			font-weight: 500;
			color: #b095ff;

			.text-underline {
				text-decoration: underline;
			}
		}
	}

	.save-btn {
		width: 690rpx;
		line-height: 86rpx;
		background: linear-gradient(-90deg, #a36fff, #5336ff);
		box-shadow: 0px 7rpx 11rpx 2rpx rgba(124, 103, 214, 0.34);
		border-radius: 43rpx;
		font-weight: 500;
		color: #ffffff;
		margin: 30rpx auto;
		display: block;
	}

	.cu-bar.foot {
		z-index: 10;
	}
</style>